package org.jeecg.modules.friends.handler;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Objects;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.friends.dao.SystemConfigDAO;
import org.jeecg.modules.friends.fetch.youzan.YouzanOrderFetch;
import org.jeecg.modules.friends.model.SystemConfigDO;
import org.jeecg.modules.friends.model.TradeOrderDO;
import org.jeecg.modules.friends.service.TradeOrderService;
import org.jeecg.modules.friends.service.VipUserService;
import org.jeecg.modules.friends.trade.dto.FullOrderInfo;
import org.jeecg.modules.friends.trade.dto.Order;
import org.jeecg.modules.friends.trade.dto.TradeOrderDetailDTO;
import org.jeecg.modules.friends.trade.dto.TradeOrderExtData;
import org.jeecg.modules.friends.user.entity.User;
import org.jeecg.modules.friends.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import lombok.extern.slf4j.Slf4j;

/**
 * @author cold
 * @version 1.0
 * @data 2024/6/21 22:20
 */
@Component
@Slf4j
public class TradeOrderCreatePushHandler extends AbstractTradeOrderHandler {
    @Autowired
    private TradeOrderService tradeOrderService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private YouzanOrderFetch youzanOrderFetch;

    @Autowired
    private IUserService userService;

    @Autowired
    private VipUserService vipUserService;

    @Autowired
    private SystemConfigDAO systemConfigDAO;


    public static final Long ZHOUKA_ID = 542674090L;
    public static final Long YUEKA_ID = 542674091L;
    public static final Long NIANKA_ID = 542674092L;


    @Override
    public String eventType() {
        return "trade_TradePaid";
    }

    @Override
    public boolean doDispatch(String eventType, String entity) {
        JSONObject msgJson = JSON.parseObject(entity);
        String msgDecode = msgJson.getString("msg");
        String orderJsonString = null;
        try {
            orderJsonString = URLDecoder.decode(msgDecode, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        log.info("收到美团订单: order :{}", orderJsonString);
        TradeOrderDetailDTO tradeOrderDetailDTO = JSON.parseObject(orderJsonString, TradeOrderDetailDTO.class);
        FullOrderInfo fullOrderInfo = tradeOrderDetailDTO.getFullOrderInfo();
        if (CollectionUtils.isNotEmpty(fullOrderInfo.getOrders())) {
            for (Order order : fullOrderInfo.getOrders()) {
                TradeOrderDO tradeOrderDO = new TradeOrderDO();
                String buyerMessage = order.getBuyerMessages();
                JSONObject jsonObject = JSON.parseObject(buyerMessage);
                if (jsonObject != null) {
                    tradeOrderDO.setBuyerPhone(jsonObject.getString("手机号"));
                }
                if (StringUtils.isEmpty(tradeOrderDO.getBuyerPhone()) && StringUtils
                        .isNotEmpty(fullOrderInfo.getBuyerInfo().getBuyerPhone())) {
                    tradeOrderDO.setBuyerPhone(
                            youzanOrderFetch.phoneDecryptClient(fullOrderInfo.getBuyerInfo().getBuyerPhone()));
                }
                tradeOrderDO.setAlias(order.getTitle());
                tradeOrderDO.setCreateTime(System.currentTimeMillis());
                tradeOrderDO.setUpdateTime(System.currentTimeMillis());
                tradeOrderDO.setNum(Integer.valueOf(order.getNum()));
                tradeOrderDO.setOrderType(1);
                tradeOrderDO.setOid(order.getOid());
                tradeOrderDO.setItemId(Long.valueOf(order.getItemId()));
                tradeOrderDO.setPrice(order.getPrice());
                tradeOrderDO.setTotalFee(order.getTotalFee());
                tradeOrderDO.setOuterUserId(fullOrderInfo.getBuyerInfo().getOuterUserId());
                tradeOrderDO.setYzOpenId(fullOrderInfo.getBuyerInfo().getYzOpenId());
                tradeOrderDO.setStatus(fullOrderInfo.getOrderInfo().getStatus());
                if (StringUtils.isNotEmpty(fullOrderInfo.getOrderInfo().getTid())) {
                    tradeOrderDO.setTid(fullOrderInfo.getOrderInfo().getTid());
                }
                String skuProperties = order.getSkuPropertiesName();
                TradeOrderExtData tradeOrderExtData = new TradeOrderExtData();
                tradeOrderExtData.setOrderSkuProperties(skuProperties);
                User user = userService.getUserByPhone(tradeOrderDO.getBuyerPhone());
                if (user != null) {
                    tradeOrderExtData.setUserId(user.getId());
                }
                tradeOrderDO.setExtData(JSON.toJSONString(tradeOrderExtData));
                tradeOrderService.save(tradeOrderDO);
                JSONArray jsonArray = JSONArray.parseArray(skuProperties);
                SystemConfigDO systemConfigDO = systemConfigDAO.findOne();
                if (Objects.nonNull(jsonArray) && jsonArray.size() > 0) {
                    int ticket = Objects.isNull(systemConfigDO) ? 7 : systemConfigDO.getTicket();
                    JSONObject jo = jsonArray.getJSONObject(0);
                    if (Objects.nonNull(user)) {
                        if (jo.getInteger("v_id") == ZHOUKA_ID.intValue()) {
                            vipUserService.addVipUser(user, 1, ticket, 7 * 24 * 3600L * 1000);
                        }
                        if (jo.getInteger("v_id") == YUEKA_ID.intValue()) {
                            vipUserService.addVipUser(user, 2, ticket, 30 * 24 * 3600L * 1000);
                        }
                        if (jo.getInteger("v_id") == NIANKA_ID.intValue()) {
                            vipUserService.addVipUser(user, 3, ticket, 365 * 24 * 3600L * 1000);
                        }
                    }
                }
            }
        }
        return false;
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        String entity =
                "{\"msg\":{\"delivery_order\":[{\"pk_id\":\"123\",\"express_state\":\"0\",\"express_type\":\"0\"}],"
                        + "\"order_promotion\":{\"item\":[{\"promotions\":[{\"promotion_type\":\"0\","
                        + "\"promotion_title\":\"满减送活动\",\"promotion_type_name\":\"满减送\",\"promotion_type_id\":\"1\","
                        + "\"decrease\":\"10.00\",\"discount_fee\":\"10.00\"}],\"is_present\":\"false\","
                        + "\"item_id\":\"123\",\"sku_id\":\"400818034\",\"oid\":\"123456\"}],"
                        + "\"order_discount_fee\":\"1.00\",\"adjust_fee\":\"1.00\",\"item_discount_fee\":\"10.00\","
                        + "\"order\":[{\"promotion_type\":\"0\",\"sub_promotion_type\":\"card\","
                        + "\"promotion_title\":\"满减送活动\",\"coupon_id\":\"3321hu2tv3123\","
                        + "\"promotion_condition\":\"满减送XX\",\"promotion_type_name\":\"满减送\","
                        + "\"promotion_content\":\"满减送XX\",\"promotion_id\":\"32382137123\","
                        + "\"promotion_type_id\":\"123\",\"discount_fee\":\"10.00\"}]},"
                        + "\"refund_order\":[{\"refund_type\":\"123\",\"refund_fee\":\"0\",\"refund_id\":\"0\","
                        + "\"refund_state\":\"2\",\"oids\":\"[]\"}],\"full_order_info\":{\"child_info\":\"{}\","
                        + "\"remark_info\":{\"star\":\"0\",\"buyer_message\":\"尽快发货\",\"trade_memo\":\"尽快支付\"},"
                        + "\"address_info\":{\"self_fetch_info\":\"{}\",\"delivery_start_time\":\"2018-01-01 "
                        + "00:00:00\",\"delivery_address\":\"学院路8888号\",\"delivery_end_time\":\"2018-01-01 "
                        + "00:00:00\",\"delivery_postal_code\":\"000000\",\"delivery_province\":\"浙江\","
                        + "\"receiver_name\":\"刘德华\",\"delivery_city\":\"杭州市\",\"address_extra\":\"{ln:23.43232,"
                        + "lat:9879.3443243}\",\"delivery_district\":\"西湖区\",\"receiver_tel\":\"15899898989\"},"
                        + "\"pay_info\":\"{ \\\"outer_transactions\\\": \\\"[]\\\", \\\"post_fee\\\": \\\"10.00\\\", "
                        + "\\\"total_fee\\\": \\\"100.99\\\", \\\"payment\\\": \\\"110.99\\\", \\\"transaction\\\": "
                        + "\\\"[]\\\" }\",\"buyer_info\":{\"outer_user_id\":\"oHIuujmVb-Rl-jrGsrSqSNPTAP-A\","
                        + "\"buyer_phone\":\"15898999998\",\"yz_open_id\":\"3hf8Fb8I596768747084054528\","
                        + "\"fans_type\":\"1\",\"buyer_id\":\"63889\",\"fans_id\":\"3233\","
                        + "\"fans_nickname\":\"ketty\"},\"orders\":[{\"tax_total\":\"0.05\","
                        + "\"is_cross_border\":\"1\",\"fenxiao_discount\":\"0.01\",\"outer_item_id\":\"ABC\","
                        + "\"item_type\":\"0\",\"discount_price\":\"0.01\",\"num\":\"100\",\"freight\":\"0.07\","
                        + "\"discount\":\"0.01\",\"fenxiao_discount_price\":\"10\",\"oid\":\"123456\","
                        + "\"title\":\"宜家水杯\",\"fenxiao_payment\":\"0.02\","
                        + "\"item_message\":\"{\\\"留言1\\\":\\\"及时快递发货\\\"}\",\"item_no\":\"spbm001\","
                        + "\"buyer_messages\":\"及时快递发货\",\"is_present\":\"false\","
                        + "\"cross_border_trade_mode\":\"1210\",\"fenxiao_freight\":\"0.07\",\"price\":\"100.00\","
                        + "\"sub_order_no\":\"E201907031647340084000141210HZ\",\"total_fee\":\"90.00\","
                        + "\"fenxiao_price\":\"0.05\",\"alias\":\"3f40ohzie8yfa\",\"payment\":\"90.00\","
                        + "\"item_barcode\":\"spbm001\",\"outer_sku_id\":\"13323\",\"goods_url\":\"https://h5.youzan"
                        + ".com/v2/goods/3f40ohzie8yfa\",\"customs_code\":\"HZ\",\"item_id\":\"123456\","
                        + "\"goods_extra\":\"{\\\\\\\"out_sku_id\\\\\\\":\\\\\\\"111\\\\\\\","
                        + "\\\\\\\"out_item_id\\\\\\\":\\\\\\\"222\\\\\\\"}\",\"pic_path\":\"https://img.com\","
                        + "\"sku_properties_name\":\"[{\\\\\\\"k\\\\\\\":\\\\\\\"净含量\\\\\\\","
                        + "\\\\\\\"k_id\\\\\\\":497,\\\\\\\"v\\\\\\\":\\\\\\\"40ml\\\\\\\","
                        + "\\\\\\\"v_id\\\\\\\":1456}]\",\"sku_id\":\"400818034\",\"points_price\":\"0\","
                        + "\"sku_no\":\"spbm001\",\"fenxiao_tax_total\":\"0.05\",\"sku_barcode\":\"spbm001\"}],"
                        + "\"out_order_info\":{\"income\":\"1000\",\"out_order_promotions\":\"[{\\\"amount\\\":300,"
                        + "\\\"partsFeeMap\\\":{},\\\"activityName\\\":\\\"减配送费3.0元\\\"}]\","
                        + "\"out_order_agent_service_fee\":\"100\",\"out_order_container_fee\":\"200\","
                        + "\"out_waybill_order_code"
                        + "\":\"ofz8V5g4UyLuZx20IozmF3_gQOb0KvSXY1ZP2kwwp5wBhtxZBo1cjeTI5ccwk9KQsdQZ24arJC6A\","
                        + "\"out_order_activity_fee_agent_part\":\"200\","
                        + "\"out_address_hash_code\":\"fb010b39dc9d5b068954789f540f71ab\","
                        + "\"out_order_no\":\"3712406698901505280\",\"out_order_activity_fee_shop_part\":\"0\"},"
                        + "\"source_info\":\"{is_offline_order:false}\",\"order_info\":{\"consign_time\":\"2018-01-01"
                        + " 00:00:00\",\"order_extra\":{\"is_from_cart\":\"false\",\"cashier_id\":\"123\","
                        + "\"fx_kdt_id\":\"123\",\"id_card_name\":\"张三\","
                        + "\"fx_inner_transaction_no\":\"2123212321212\",\"invoice_title\":\"抬头\","
                        + "\"is_sub_order\":\"false\",\"cashier_name\":\"收银员\",\"is_points_order\":\"false\","
                        + "\"settle_time\":\"1525844042082\",\"fx_outer_transaction_no\":\"2123212321212\","
                        + "\"daogou\":\"{\\\"name\\\":\\\"张三\\\",\\\"id\\\":\\\"9408645\\\"}\","
                        + "\"merchant_customized_special_order\":\"1\",\"is_parent_order\":\"false\","
                        + "\"id_card_number\":\"123\",\"fx_order_no\":\"E2018\",\"dept_id\":\"123\","
                        + "\"parent_order_no\":\"E2018\",\"purchase_order_no\":\"E2018\","
                        + "\"create_device_id\":\"123\"},\"created\":\"2018-01-01 00:00:00\",\"offline_id\":\"0\","
                        + "\"status_str\":\"已付款\",\"expired_time\":\"2018-01-01 00:00:00\","
                        + "\"success_time\":\"2018-01-01 00:00:00\",\"type\":\"0\",\"tid\":\"E20180101111112340001\","
                        + "\"confirm_time\":\"2018-01-01 00:00:00\",\"pay_time\":\"2018-01-01 00:00:00\","
                        + "\"update_time\":\"2018-01-01 00:00:00\",\"is_retail_order\":\"false\",\"team_type\":\"0\","
                        + "\"pay_type\":\"0\",\"refund_state\":\"0\",\"close_type\":\"0\","
                        + "\"status\":\"WAIT_BUYER_PAY\",\"express_type\":\"0\","
                        + "\"order_tags\":{\"is_virtual\":\"false\",\"is_purchase_order\":\"false\","
                        + "\"is_member\":\"false\",\"is_preorder\":\"false\",\"is_offline_order\":\"false\","
                        + "\"is_multi_store\":\"false\",\"is_settle\":\"false\",\"is_payed\":\"false\","
                        + "\"is_secured_transactions\":\"false\",\"is_postage_free\":\"false\","
                        + "\"is_fenxiao_order\":\"false\",\"is_feedback\":\"false\",\"is_refund\":\"false\"}},"
                        + "\"channel_info\":{\"app_name\":\"sph小店\",\"type\":\"WX\",\"entrance\":\"wx_video_xd\","
                        + "\"app_id\":\"wx460fed3dbb499999\"}}},\"kdt_name\":\"云测试店铺vCY6J191010191128200711\","
                        + "\"kdt_id\":\"90731021\",\"id\":\"E20201216171450086900211\","
                        + "\"type\":\"trade_TradeCreate\",\"msg_id\":\"1d2ba0ac-e08a-4979-bcdb-72b091088d3e\","
                        + "\"version\":\"1608186739\",\"app_id\":\"1\",\"root_kdt_id\":\"43387399\","
                        + "\"status\":\"WAIT_BUYER_PAY\"}";
        JSONObject msgJson = JSON.parseObject(entity);
        String msgDecode = msgJson.getString("msg");
        String orderJsonString = URLDecoder.decode(msgDecode, "UTF-8");
        log.info("收到美团订单: order :{}", orderJsonString);
        TradeOrderDetailDTO tradeOrderDetailDTO = JSON.parseObject(orderJsonString, TradeOrderDetailDTO.class);
        FullOrderInfo fullOrderInfo = tradeOrderDetailDTO.getFullOrderInfo();
        System.out.println(JSON.toJSON(fullOrderInfo));
    }
}
